package com.banciyuan.bcywebview.biz.circles.smooth.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CircleApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.circles.smooth.adapter.CircleSmoothHotAdapter;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import de.greenrobot.daoexample.model.DiscoverData;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Timeline;


/**
 * Created by squall on 2016/9/30.
 */

public class CircleSmoothHotFragment extends CircleBaseSmoothFragment {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private CircleSmoothHotAdapter circleSmoothHotAdapter;
    private List<Timeline> tlist = new LinkedList<>();
    private String since = "0";
    private DiscoverData discoverData;
    private List<Timeline> tempList = new LinkedList<>();

    private boolean isRelaEnd;
    private boolean isDataEnd;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.circle_smooth_fragment, null);
        initArgs();
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        getHeader();
        initData();
    }

    @Override
    protected void initArgs() {
        super.initArgs();
    }

    @Override
    protected void initUi(View rootview) {
        recyclerView = (RecyclerView) rootview.findViewById(R.id.recycle);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        swipeRefreshLayout = (SwipeRefreshLayout) rootview.findViewById(R.id.swipe);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        swipeRefreshLayout.setProgressViewOffset(false, UIUtils.dip2px(205, getActivity()) + getOffset(), UIUtils.dip2px(280, getActivity()) + getOffset());
        swipeRefreshLayout.setColorSchemeResources(R.color.pink, R.color.pink);
        circleSmoothHotAdapter = new CircleSmoothHotAdapter(getActivity(), tlist, true);
        recyclerView.setAdapter(circleSmoothHotAdapter);
    }

    @Override
    protected void initAction() {
        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (dy < 0) {
                    if (ll.findFirstVisibleItemPosition() == 0 && ll.getChildAt(ll.findFirstVisibleItemPosition()).getTop() > -UIUtils.dip2px(108, getActivity())) {
                        onFoldScrollListener.onScroll(dy);
                    }
                } else {
                    onFoldScrollListener.onScroll(dy);
                }
            }

            @Override
            public void onTop() {
                onFoldScrollListener.onTop();
            }

            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    page++;
                    initData();
                }
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                end_flag = false;
                isDataEnd = false;
                isRelaEnd = false;
                page = 1;
                since = "0";
                getHeader();
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> pairs = new ArrayList<>();
        String url;
        if ("work".equals(type)) {
            url = HttpUtils.BASE_URL + CircleApi.getHotworks();
            pairs.add(new BcyPair(HttpUtils.ID, id));
        } else {
            url = HttpUtils.BASE_URL + CircleApi.getHotTags();
            pairs.add(new BcyPair(HttpUtils.NAME, name));
        }
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SINCE, since));
        HashMap<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray result = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        tempList = TimelineFactory.createTimeline(result);
                        isDataEnd = true;
                        checkend();
                    } catch (Exception e) {
                        isDataEnd = true;
                        checkend();
                    }
                } else {
                    isDataEnd = true;
                    checkend();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDataEnd = true;
                checkend();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private void getHeader() {
        discoverData = (DiscoverData) getArguments().getSerializable("rela");
        isRelaEnd = true;
        checkend();
    }

    private void checkend() {
        if (isDataEnd && isRelaEnd) {
            renderTimeline(tempList);
            loading = false;
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    private void addLocalCard(List<Timeline> templist, DiscoverData discoverData) {
        if (templist != null) {
            switch (templist.size()) {
                case 0:
                    templist.add(getHeaderTimeline(discoverData));
                    templist.add(getGoodsTimeline(discoverData));
                    templist.add(getPostRankTimeline(discoverData));
                    templist.add(getEmptyTimeline());
                    break;
                case 1:
                    templist.add(0, getHeaderTimeline(discoverData));
                    templist.add(getGoodsTimeline(discoverData));
                    templist.add(getPostRankTimeline(discoverData));
                    break;
                case 2:
                    templist.add(0, getHeaderTimeline(discoverData));
                    templist.add(getGoodsTimeline(discoverData));
                    templist.add(getPostRankTimeline(discoverData));
                    break;
                case 3:
                    templist.add(0, getHeaderTimeline(discoverData));
                    templist.add(3, getGoodsTimeline(discoverData));
                    templist.add(5, getPostRankTimeline(discoverData));
                    break;
                default:
                    templist.add(0, getHeaderTimeline(discoverData));
                    templist.add(3, getGoodsTimeline(discoverData));
                    templist.add(6, getPostRankTimeline(discoverData));
                    break;
            }
        }
    }

    private Timeline getPostRankTimeline(DiscoverData discoverData) {
        Timeline timeline = new Timeline();
        if (discoverData.getPost_rank() != null) {
            timeline.setPost_rank(discoverData.getPost_rank());
            timeline.setOtype_data("local");
            timeline.setOtype("local");
        } else {
            timeline.setOtype_data("illegal_type");
            timeline.setOtype("illegal_type");
        }
        return timeline;
    }

    private Timeline getHeaderTimeline(DiscoverData discoverData) {
        Timeline timeline = new Timeline();
        if (discoverData.getAffiche() != null && !TextUtils.isEmpty(discoverData.getAffiche().getText())) {
            timeline.setAffiche(discoverData.getAffiche());
        }
        if (discoverData.getRela() != null && !discoverData.getRela().isEmpty()) {
            timeline.setRela(discoverData.getRela());
        }
        timeline.setOtype_data("local");
        timeline.setOtype("local");
        return timeline;
    }

    private Timeline getGoodsTimeline(DiscoverData discoverData) {
        Timeline timeline = new Timeline();
        if (discoverData.getGoods_data() != null && !discoverData.getGoods_data().isEmpty()) {
            timeline.setGoods_data(discoverData.getGoods_data());
            timeline.setGoods_count(discoverData.getGoods_count());
            timeline.setOtype_data("local");
            timeline.setOtype("local");
        } else {
            timeline.setOtype_data("illegal_type");
            timeline.setOtype("illegal_type");
        }

        return timeline;
    }

    private Timeline getEmptyTimeline() {
        Timeline timeline = new Timeline();
        timeline.setOtype(MyConstants.OTYPE_EMPTY);
        timeline.setOtype_data(MyConstants.OTYPE_EMPTY);
        return timeline;
    }

    private void renderTimeline(List<Timeline> templist) {
        String ctime = ignoreTagName(templist);
        if (StringUtil.notNullEqual(since, "0")) {
            tlist.clear();
            if (discoverData != null) {
                addLocalCard(templist, discoverData);
            }
        }
        TimelineFactory.popCircleIllegalItem(templist);
        tlist.addAll(templist);
        if (circleSmoothHotAdapter != null) {
            circleSmoothHotAdapter.setLoading(false);
            if (StringUtil.notNullEqual(since, "0")) {
                circleSmoothHotAdapter.setHeight(0);
                circleSmoothHotAdapter.setMax(-1);
                circleSmoothHotAdapter.notifyDataSetChanged();
            } else {
                if (!templist.isEmpty()) {
                    circleSmoothHotAdapter.notifyItemChanged(circleSmoothHotAdapter.getItemCount() - 1);
                    circleSmoothHotAdapter.notifyItemRangeInserted(tlist.size() - templist.size() + 1, templist.size());
                }
            }
        } else {
            circleSmoothHotAdapter = new CircleSmoothHotAdapter(getActivity(), tlist, false);
            recyclerView.setAdapter(circleSmoothHotAdapter);
        }
        if (!templist.isEmpty()) {
            since = ctime;
        } else {
            end_flag = true;
        }
        loading = false;
        swipeRefreshLayout.setRefreshing(false);
    }


    private String ignoreTagName(List<Timeline> templist) {
        String ctime;
        if (!templist.isEmpty()) {
            ctime = templist.get(templist.size() - 1).getPushtime();
            if (TextUtils.isEmpty(ctime)) {
                ctime = "0";
            }
            for (Timeline t : templist) {
                List<TagDetail> tlist = new ArrayList<>();
                for (TagDetail tag : t.getTags()) {
                    boolean is_work = StringUtil.notNullEqual(tag.getWid(), id);
                    if (!tag.getTag_name().equalsIgnoreCase(name) && !is_work) {
                        tlist.add(tag);
                    }
                }
                t.setTags(tlist);
            }
        } else {
            ctime = "0";
        }
        return ctime;
    }


    @Override
    public void getParentHeight(int height) {
        if (!isVisibleToUser) {
            LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
            int index = ll.findFirstVisibleItemPosition();
            if (index == 0 || index == -1) {
                ll.scrollToPositionWithOffset(0, height);
            }
        }
    }
}
